package com.chaoxinet.csmall.passport.security;

import com.chaoxinet.csmall.passport.mapper.AdminMapper;
import com.chaoxinet.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 西风残叶
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    /**
     * 重写loadUserByUsername方法，用于加载用户信息
     * @param s 用户名
     * @return UserDetails对象，包含用户信息
     * @throws UsernameNotFoundException 如果用户名不存在，则抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 获取管理员登录信息
        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(s);
        log.info("Spring Security调用了loadUserByUsername方法,参数为:{},结果为:{}",s,loginInfo);

        // 如果登录信息为空，则返回null
        if (loginInfo==null){
            return null;
        }

        // 获取用户名和启用状态
        log.info("username:{}",loginInfo.getUsername());
        log.info("enable:{}",loginInfo.getEnable());

        // 判断用户名是否匹配
        if (s.equals(loginInfo.getUsername())) {
            List<String> permissions = loginInfo.getPermissions();
            // 创建权限列表
            List<GrantedAuthority> authorities = new ArrayList<>();
            // 创建权限的授权
            for (String permission : permissions) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
                authorities.add(authority);
            }

            // 创建AdminDetails对象
            AdminDetails adminDetails = new AdminDetails(
                    loginInfo.getId(),
                    loginInfo.getUsername(),
                    loginInfo.getPassword(),
                    loginInfo.getEnable()==1,
                    authorities);

            log.debug("即将向Spring Security返回AdminDetails对象:{}",adminDetails);

            return adminDetails;
        }

        return null;
    }
}